package database

import (
	"sync"
)

type TTLDict struct {
	// 超时槽, key:超时时间(秒), value:超时的Key槽([]string)
	ttlMap sync.Map
	// 基准时间
	//baseTime time.Time
}

func MakeTTLDict() *TTLDict {
	return &TTLDict{
		//baseTime: time.Now(),
	}
}

// Add 添加超时的Key
func (this *TTLDict) Add(key string, expire int, lastSlotTime int) int {
	// timeSub := util.TimeSince(this.baseTime, time.Now())
	slotTime := lastSlotTime + expire
	keySlcItf, ok := this.ttlMap.Load(slotTime)
	if ok {
		// 已经存在相同超时槽,存入槽中
		keySlc, ok := keySlcItf.([]string)
		if ok {
			keySlc = append(keySlc, key)
		}
	} else {
		// 不存在则添加新的超时槽
		keySlc := make([]string, 0)
		keySlc = append(keySlc, key)
		this.ttlMap.Store(slotTime, keySlc)
	}
	// util.PrintTime(fmt.Sprintf("key:%s,expire:%d,slotTime:%d,map:%v\n", key, expire, slotTime, this.ttlMap))
	return slotTime
}

// Get 获取超时的Key槽
func (this *TTLDict) Get(expire int) []string {
	keySlcItf, ok := this.ttlMap.Load(expire)
	if ok {
		keySlc := keySlcItf.([]string)
		return keySlc
	} else {
		return nil
	}
}

// Update 更新Key的超时时间
func (this *TTLDict) Update(key string, expire int, oldSlotTime int, lastSlotTime int) int {
	keySlcItf, ok := this.ttlMap.Load(oldSlotTime)
	if ok {
		keySlc := keySlcItf.([]string)
		// 在原来的槽位上删除key
		for i := 0; i < len(keySlc); i++ {
			if keySlc[i] == key {
				keySlc = append(keySlc[:i], keySlc[i+1:]...)
				break
			}
		}
		this.ttlMap.Store(oldSlotTime, keySlc)
	}
	// 添加到新的槽位
	return this.Add(key, expire, lastSlotTime)
}

// Delete 删除已经超时的槽位
func (this *TTLDict) Delete(timeSub int) {
	this.ttlMap.Delete(timeSub)
}
